package com.example.controller;

import com.example.common.Result;
import com.example.common.enums.RoleEnum;
import com.example.entity.Account;
import com.example.entity.User;
import com.example.service.AdminService;
import com.example.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

@RestController
public class WebController {

    @Resource
    private AdminService adminService;
    @Autowired
    private UserService userService;
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    /**
     * 默认请求接口
     */
    @GetMapping("/")
    public Result hello () {
        return Result.success();
    }

    /**
     * 登录
     */
    @PostMapping("/login")
    @ResponseBody
    public Result login(@RequestBody Account account) {
        Result result = new Result();
        /*if (RoleEnum.ADMIN.name().equals(account.getRole())) {
            loginAccount = adminService.login(account);
        }*/
        try{
            User user = userService.selectByPhoneOrEmail(account.getUsername());
            if(user != null){
                boolean flag = passwordEncoder.matches(account.getPassword(), user.getPassword());
                if(flag){
                    result.setCode("200");
                    result.setMsg("登录成功");
                    result.setData(user);
                }else{
                    result.setCode("500");
                    result.setMsg("用户名或密码错误");
                }
            }else{
                result.setCode("500");
                result.setMsg("不存在该用户");
            }
        }catch (Exception e){
            e.printStackTrace();
            result.setCode("500");
            result.setMsg("登录异常");
        }
//        return Result.success(loginAccount);
        return result;
    }

    /**
     * 注册
     */
    @PostMapping("/register")
    @ResponseBody
    public Result register(@RequestBody User user) {
        Result result = new Result();
        try{
            System.out.println(user);
            if(userService.add(user)){
                result.setCode("200");
                result.setMsg("注册成功");
            }else{
                result.setCode("500");
                result.setMsg("已存在该用户名");
            }
        }catch (Exception e){
            e.printStackTrace();
            result.setCode("500");
            result.setMsg("注册失败");
        }
        return result;
    }

    /**
     * 修改密码
     */
    @PutMapping("/updatePassword")
    public Result updatePassword(@RequestBody Account account) {
        if (RoleEnum.ADMIN.name().equals(account.getRole())) {
            adminService.updatePassword(account);
        }
        return Result.success();
    }

}
